package com.amlyc.ch03;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockDemo {
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
    private static ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    private static int value = 0;
    public Object read(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        }finally {
            lock.unlock();
        }


    }
    public void write(Lock lock) throws InterruptedException {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = new Random().nextInt();
        }finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) throws InterruptedException {
        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                try {
                    readWriteLockDemo.read(readLock);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                try {
                    readWriteLockDemo.write(writeLock);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        for (int i = 0; i < 20; i++) {
            new Thread(r1);
        }
        for (int i = 0; i < 50; i++) {
            new Thread(r2);
        }

        Thread.sleep(20000);
    }


}
